<?php
//导出  header
function exportHeader($EXCEL_OUT)
{
    header("Content-type:text/csv");
    header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
    header('Expires:0');
    header('Pragma:public');
    echo $EXCEL_OUT;
}

//判断是否含有英文逗号，英文引号
function Check($str)
{
    $str = str_replace(array("\r\n", "\r", "\n"), "", $str);
    if (strpos($str, ',')) {
        if (strpos($str, "\"") || strpos($str, "\"") == 0) {
            $str = str_replace("\"", "\"\"", $str);
        }
        $str = "\"" . $str . "\"";
    } else {
        $str = "\"\t" . $str . "\"";
    }
    return $str;
}

function flagOrder($list){
  $title = "序号,订单号,用户,商户名,是否自营,商品名,商品信息,收件人,电话,地址,总金额（含运费）,运费,订单状态,快递单号,快递公司,下单时间";
  $title .= "\n";
  $EXCEL_OUT = iconv('UTF-8', 'GB2312', $title);
  foreach ($list as $index => $value) {
      $out = array();
      $out[] = $index + 1;
      $out[] = trim("\"\t" . $value['tran_no'] . "\"");
      $out[] = trim(Check($value['user_name']));
      $out[] = trim(Check($value['shop_name']));
      $out[] = ($value['is_platform'] == 1) ? "自营" : "";

      $out[] = Check($value['product_name']);
      $goods_str = "";//商品信息
      if($value['spec_id']){
          $goods_str .= "规格：" . $value['product_spec'] . "，";
          $goods_str .= "数量：" . $value['product_num'] . "，";
          $goods_str .= "小计：" . $value['product_price'] . "元";
          $goods_str .= "；";
      }else{
          $goods_str .= "数量：" . $value['product_num'] . "，";
          $goods_str .= "小计：" . $value['product_price'] . "元";
          $goods_str .= "；";
      }
      $out[] = Check($goods_str);

      $out[] = Check($value['receiver_name']);
      $out[] = trim("\"\t" . $value['receiver_mobile'] . "\"");
      $out[] = Check($value['province'].$value['city'].$value['area']);
      $out[] = $value['total_amount'] . "元";
      $out[] = $value['delivery_amount'] . "元";

      $status = '';
      switch ($value['status']) {
        case 1:
          $status = '未支付';
          break;
        case 2:
          $status = "已支付（待发货）";
          break;
        case 3:
          $status = "已取消";
          break;
        case 4:
          $status = "已发货";
          break;
        case 5:
          $status = "已收货";
          break;
        case 6:
          $status = "申请退款";
          break;
        case 7:
          $status = "已完成";
          break;
        case 8:
          $status = "已退款";
          break;
        case 9:
          $status = "拒绝退款";
          break;
        case 10:
          $status = "同意退款";
          break;
        default:
          $status = "异常订单";
          break;
      };

      $out[] = Check($status);
      $out[] = Check($value['exp_no']);
      $out[] = Check($value['exp_company']);

      $out[] = trim("\"\t" . date('Y-m-d H:i', $value['created_at']) . "\"");
      $EXCEL_OUT .= mb_convert_encoding(implode(',', $out) . "\n", 'GB2312', 'UTF-8');//需要先启用 mbstring 扩展库，在 php.ini里将; extension=php_mbstring.dll 前面的 ; 去掉
  }

  $name = "订单导出-" . date('YmdHis', time()); //导出文件名称 
  header("Content-Disposition:attachment;filename={$name}.csv"); //“生成文件名称”=自定义

  exportHeader($EXCEL_OUT);
  exit(); 

}

function flagAmount($list){
    $title = "序号,商户名,提现金额,实际金额,提现比率,状态,申请类型,申请时间";
    $title .= "\n";
    $EXCEL_OUT = iconv('UTF-8', 'GBK', $title);
    foreach ($list as $index => $value) {
        $out = array();
        $out[] = $index + 1;
        $out[] = trim("\"\t" . $value['shop_name'] . "\"");
        $out[] = $value['total_amount'] . "元";
        $out[] = $value['amount'] . "元";
        $out[] = Check($value['rate']);
        $status = '';$types = '';

        switch ($value['status']) {
          case 1:
            $status = '余额记录';
            break;
          case 2:
            $status = "未打款";
            break;
          case 3:
            $status = "已打款";
            break;
          case 4:
            $status = "已拒绝";
            break;
          default:
            $status = "未知";
            break;
        }
        switch ($value['types']) {
          case 1:
            $types = '余额提现';
            break;
          case 2:
            $types = "返利提现";
            break;
          default:
            $types = "余额提现";
            break;
        }
        $out[] = Check($status);
        $out[] = Check($types);
        $out[] = trim("\"\t" . date('Y-m-d H:i', $value['created_at']) . "\"");
        $EXCEL_OUT .= mb_convert_encoding(implode(',', $out) . "\n", 'GB2312', 'UTF-8');
    }

    $name = "记录-" . date('YmdHis', time());//导出文件名称
    header("Content-Disposition:attachment;filename={$name}.csv"); //“生成文件名称”=自定义
    exportHeader($EXCEL_OUT);
    exit();
}

function flagGoods($list){
    $title = "序号,商户名,商品名称,销售数量,销售总额,价格,库存,创建时间";
    $title .= "\n";
    $EXCEL_OUT = iconv('UTF-8', 'GBK', $title);

    foreach ($list as $index => $value) {
        $out = array();
        $out[] = $index + 1;
        $out[] = trim("\"\t" . $value['shop_name'] . "\"");
        $out[] = trim("\"\t" . $value['pname'] . "\"");
        $out[] = Check($value['num']);
        $out[] = $value['amount'] . "元";
        $out[] = $value['price'] . "元";
        $out[] = Check($value['product_num']);
        $out[] = Check(date("Y-m-d H:i:s", $value['created_at']));
        $EXCEL_OUT .= mb_convert_encoding(implode(',', $out) . "\n", 'GB2312', 'UTF-8');
    }

    $name = "商品销量-" . date('YmdHis', time());//导出文件名称
    header("Content-Disposition:attachment;filename={$name}.csv"); //“生成文件名称”=自定义
    exportHeader($EXCEL_OUT);
    exit();
}

function flagSales($list){
    $title = "序号,商户名,销售数量,销售总额,店铺状态,店铺创建";
    $title .= "\n";
    $EXCEL_OUT = iconv('UTF-8', 'GBK', $title);

    foreach ($list as $index => $value) {
        $out = array();
        $out[] = $index + 1;
        $out[] = trim("\"\t" . $value['shop_name'] . "\"");
        $out[] = Check($value['num']);
        $out[] = $value['amount'] . "元";
        $out[] = Check($value['status']==1?'开启':'关闭');
        $out[] = Check(date("Y-m-d H:i:s", $value['created_at']));
        $EXCEL_OUT .= mb_convert_encoding(implode(',', $out) . "\n", 'GB2312', 'UTF-8');
    }

    $name = "店铺销量-" . date('YmdHis', time());//导出文件名称
    header("Content-Disposition:attachment;filename={$name}.csv"); //“生成文件名称”=自定义
    exportHeader($EXCEL_OUT);
    exit();
}
function flagWithdraw($list){
    $title = "序号,商铺ID,商户名,累计提现,可提现,可返利,店铺状态,店铺创建";
    $title .= "\n";
    $EXCEL_OUT = iconv('UTF-8', 'GBK', $title);

    foreach ($list as $index => $value) {
        $out = array();
        $out[] = $index + 1;
        $out[] = Check($value['id']);
        $out[] = trim("\"\t" . $value['shop_name'] . "\"");
        $out[] = $value['total_amount'] . "元";
        $out[] = $value['amount'] . "元";      
        $out[] = $value['brokerage'] . "元";
        $out[] = Check($value['status']==1?'开启':'关闭');
        $out[] = Check(date("Y-m-d H:i:s", $value['created_at']));
        $EXCEL_OUT .= mb_convert_encoding(implode(',', $out) . "\n", 'GB2312', 'UTF-8');
    }

    $name = "店铺提现-" . date('YmdHis', time());//导出文件名称
    header("Content-Disposition:attachment;filename={$name}.csv"); //“生成文件名称”=自定义
    exportHeader($EXCEL_OUT);
    exit();
}
/**
*  /分页---num--数据数量 get_page_list
*/

//html分页
function get_html_page_list($url_name, $list=array(), $last=1, $limit=10, $num=0, $where=array())
{
  $page['list']=$list?$list:array();

  //搜索条件
  $str="";
  if ($where) {
    $str="&".ToUrlParams($where);
  }

  $page_num=ceil($num/$limit);
  if ($page_num<1) {
    $page['page']=array();
  } else {
    $page['page']['first']['page']=1;
    $page['page']['first']['href']=U($url_name, array("page"=>1)).$str;
    $page['page']['last']['page']= $page_num;
    $page['page']['last']['href']=U($url_name, array("page"=>$page_num)).$str;

    if ($page_num>=$last) {

    //确定起始页
      if ($last<5) {
        $beg_page=1;
      } elseif ($last%5!=0) {
        $beg_page=floor($last/5)*5+1;
      } else {
        $beg_page=$last-4;
      }

      //每五个记录一个循环
      if ($last-5>1) {
        $front=$beg_page-5;
        $page['page']['front']['page']=$front;
        $page['page']['front']['href']=U($url_name, array("page"=>$front)).$str;
      } else {
        $page['page']['front']=$page['page']['first'];
      }

      if ($page_num-$last>=1) {
        $after=$beg_page+5;
        $page['page']['after']['page']=$after;
        $page['page']['after']['href']=U($url_name, array("page"=>$after)).$str;
      } else {
        $page['page']['after']=$page['page']['last'];
      }

      //显示5页
      if ($page_num>=$beg_page+4) {
        $xs_num=5;
      } else { //显示不足5页
        $xs_num=$page_num-$beg_page+1;
      }

      for ($i=0; $i <$xs_num ; $i++) {
        $page_index=$beg_page+$i;
        $pages[$i]['index']=0;
        if ($page_index==$last) {
          $pages[$i]['index']=1;
        }
        $pages[$i]['page']=$page_index;
        $pages[$i]['href']=U($url_name, array("page"=>$page_index)).$str;
      }

      $page['page']['list']=$pages;
    } else {
      $page['page']['list']=array();
    }
  }

  return $page;
}


function file_upload($app_id)
{
  if (!$app_id) {
    return false;
  }

  $storage_config = D('apps')->storage_config($app_id);

  switch ($storage_config['storage_type']) {
    case 1:
      $upload_config = array(
        'host' => $storage_config['upyun_host'],
        'bucket' => $storage_config['upyun_bucket'],
        'username' => $storage_config['upyun_username'],
        'password' => $storage_config['upyun_password'],
        'endpoint' => $storage_config['upyun_endpoint']
      );
      $upload_type = 'Upyun';
      $domain = $storage_config['upyun_endpoint'];
      break;
    case 2:
      $upload_config = array(
        'AccessKeyId' => $storage_config['oss_key'],
        'AccessKeySecret' => $storage_config['oss_secret'],
        'domain' => $storage_config['oss_domain'],
        'Bucket' => $storage_config['oss_bucket'],
        'Endpoint' => $storage_config['oss_endpoint']
      );
      $upload_type = 'Aliyun';
      $domain = $storage_config['oss_domain'];
      break;
    case 3:
      $upload_config = array(
        'secretKey' => $storage_config['qiniu_secretkey'],
        'accessKey' => $storage_config['qiniu_accesskey'],
        'domain' => $storage_config['qiniu_domain'],
        'bucket' => $storage_config['qiniu_bucket'],
        'area' => $storage_config['qiniu_area']
      );

      $upload_type = 'Qiniu';
      $domain = $storage_config['qiniu_domain'];
      break;
  }

  $upload = new \Think\Upload(array(), $upload_type, $upload_config);
  $upload->rootPath = './';
  $month = date('Ym');
  $upload->savePath = "{$month}/";

  $upload->autoSub = false;
  $info = $upload->upload();

  if ($info) {
    foreach ($info as $file) {
      $files[] = "$domain/{$month}/$file[savename]";
    }
  }

  return $files;
}

function send_payed_message_to_shop($log_id)
{
  $log = M('amount_logs')->alias('l')
                         ->join("left join ".C("DB_PREFIX")."shops s on s.id=l.shop_id")
                         ->join("left join ".C("DB_PREFIX")."users u on u.shop_id=s.id")
                         ->join("left join ".C("DB_PREFIX")."apps a on u.app_id=a.id")
                         ->where("l.id=$log_id")
                         ->field('l.*, u.xcx_openid, u.app_id, a.pay_to_shop_template_id')
                         ->find();
  // $date = date('Y-m-d H:i:s', time());
  $params = array(
    'xcx_openid' => $log['xcx_openid'],
    'template_id' => $log['pay_to_shop_template_id'],
    'form_id' => $log['form_id'],
    'data' => array(
      'keyword1' => array('value' => "{$log['amount']}元", 'color' => '#173177'),
      'keyword2' => array('value' => '请到小程序提现结算明细下查看。', 'color' => '#173177'),
    ),
    'page' => 'pages/shop/withdraw'
  );

  $result = send_app_msg($params, $log['app_id']);
}

function send_withdraw_reject_message_to_shop($log_id)
{
  $log = M('amount_logs')->alias('l')
                         ->join("left join ".C("DB_PREFIX")."shops s on s.id=l.shop_id")
                         ->join("left join ".C("DB_PREFIX")."users u on u.shop_id=s.id")
                         ->join("left join ".C("DB_PREFIX")."apps a on u.app_id=a.id")
                         ->where("l.id=$log_id")
                         ->field('l.*, u.xcx_openid, u.app_id, a.withdraw_reject_template_id')
                         ->find();
  // $date = date('Y-m-d H:i:s', time());
  $log['types_str'] = $log['types'] == 1 ? '余额提现' : '返利提现' ;

  $params = array(
    'xcx_openid' => $log['xcx_openid'],
    'template_id' => $log['withdraw_reject_template_id'],
    'form_id' => $log['form_id'],
    'data' => array(
      'keyword1' => array('value' => $log['types_str'], 'color' => '#173177'),
      'keyword2' => array('value' => $log['reject_reason'], 'color' => '#173177'),
    ),
    'page' => 'pages/shop/withdraw'
  );

  $result = send_app_msg($params, $log['app_id']);
}
